#include "BSP/system.h"

#include "time.h"

#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <BSP/ticks.h>

PRIVATE uint8_t mStrTxBuffer[BSP_STRING_BUFFER_SIZE];

#define SECOND_RATIO      (1)
#define MILLISECOND_RATIO (SECOND_RATIO * 1000)
#define MICROSECOND_RATIO (MILLISECOND_RATIO * 1000)
#define CLOCKS_PER_SEC (200)

PRIVATE void delay(clock_t ticks);

int32_t BSP_Init(void)
{
    return ERROR_NONE_EC;
}

void BSP_DelayUs(uint32_t us)
{
    clock_t _tmpTicks = us * (CLOCKS_PER_SEC / MICROSECOND_RATIO);

    return delay(_tmpTicks);
}
void BSP_DelayMs(uint32_t ms)
{
    clock_t _tmpTicks = ms * (CLOCKS_PER_SEC / MILLISECOND_RATIO);
    return delay(_tmpTicks);
}
uint64_t BSP_GetTicks(void)
{
    return BSP_TicksGetTick();
}
uint64_t BSP_GetSysTime(void)
{
    return BSP_GetTicks() / (CLOCKS_PER_SEC / MICROSECOND_RATIO);
}
uint64_t BSP_GetSysTimeNs(void)
{
    return BSP_GetTicks();
}
void BSP_Printf(String fmt, ...)
{
    va_list arg_ptr;

    va_start(arg_ptr, fmt);
    vsprintf((char *)mStrTxBuffer, fmt, arg_ptr);
    va_end(arg_ptr);

    printf("%s", (char *)mStrTxBuffer);
}

PRIVATE void delay(clock_t ticks)
{
    uint32_t i = 0;

    for (i = 0; i < ticks; i++)
    {
        asm volatile("nop;;");
    }
}